package com.kye.express.business.jd.goods_detail;

import android.content.Context;

import com.kye.express.business.jd.goods_detail.model.JDAddressModel;
import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.IView;
import com.kye.express.view.ToastManager;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.UserSession;
import com.kye.model.base.Data4ResultSet;
import com.kye.model.base.PageInfo;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.integral.IntegralUserBean;
import com.kye.model.bean.integral.request.RequestUserIntegral;
import com.kye.model.bean.jd.address.JDAddressBean;
import com.kye.model.bean.jd.address.request.RequestJDAddress;
import com.kye.model.bean.jd.goods_detail.JDCheckGoodsAvailableResultBean;
import com.kye.model.bean.jd.goods_detail.JDGoodsDetailInfoBean;
import com.kye.model.bean.jd.goods_detail.RequestJDCheckGoodsAvailable;
import com.kye.model.bean.jd.goods_detail.RequestJDGoodsDetail;
import com.kye.model.bean.jd.shop.JDCheckConsumeAvailableResultBean;
import com.kye.model.bean.jd.shop.JDCheckUploadAddressAvailableResultBean;
import com.kye.model.bean.jd.shop.JDGoodsItemBean;
import com.kye.model.bean.jd.shop.JDGoodsListResultBean;
import com.kye.model.bean.jd.shop.JDGoodsSkuImageBean;
import com.kye.model.bean.jd.shop.request.RequestJDCheckConsumeAvailable;
import com.kye.model.bean.jd.shop.request.RequestJDCheckUploadAddressAvailable;
import com.kye.model.bean.jd.shop.request.RequestJDGoodsList;
import com.kye.model.bean.user.User;
import com.kye.model.datasource.IntegralDataSource;
import com.kye.model.datasource.JDShopDataSource;
import com.kye.model.gson_adapter.ApiException;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.SingleSource;
import io.reactivex.SingleTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Function4;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 18/12/2017
 * @updated : 18/12/2017
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public interface JDGoodsDetailContract {

    interface JDGoodsDetailView extends IView {

        void onUser(User userInfo);

        void refreshSuccess(Data4ResultSet<OpenApiResult<IntegralUserBean>, OpenApiResult<JDGoodsListResultBean>, OpenApiResult<JDGoodsDetailInfoBean>, OpenApiResult<List<JDAddressBean>>> data4ResultSet);

        void refreshServerFailed(String message);

        void refreshNetFailed(String message);

        void showJDAddressSelectionBottomSheet(List<JDAddressModel> jdAddressModels);

        void onLoading();

        void onLoaded();

        void checkGoodsAvailableSuccess(JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean);

        void checkGoodsAvailableServerFailed(String msg);

        void checkGoodsAvailableNetFailed(String message);

        void updateGoodsAddressNoAddress();

        void checkGoodsAvailableSuccessFirst(JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean);

        void checkGoodsAvailableServerFailedFirst(String msg);

        void checkGoodsAvailableNetFailedFirst(String message);

        void checkGoodsUnAvailableSuccess(OpenApiResult<JDCheckGoodsAvailableResultBean> result);

        void checkGoodsUnAvailableSuccessFirst(OpenApiResult<JDCheckGoodsAvailableResultBean> result);

        List<JDAddressModel> getJdAddressModels();

        void setJdAddressModels(List<JDAddressModel> jdAddressModels);

        JDAddressModel getPreSelectedAddress();

        void setPreSelectedAddress(JDAddressModel preSelectedAddress);

        JDAddressModel getSelectedAddress();

        void setSelectedAddress(JDAddressModel selectedAddress);

        void checkGoodsAvailableFromAddressManageSuccess(JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean);

        void checkGoodsUnAvailableFromAddressManageSuccess(OpenApiResult<JDCheckGoodsAvailableResultBean> result);

        void checkGoodsAvailableFromAddressManageServerFailed(String msg);

        void checkGoodsAvailableNetFromAddressManageFailed(String message);

        Context getContext();

        @Deprecated
        void checkStateBeforeExchange();

        void toExchangePage(JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean);
    }

    class JDGoodsDetailPresenter extends BasePresenter<JDGoodsDetailView> {

        private JDShopDataSource jdShopDataSource;
        private IntegralDataSource integralDataSource;

        public JDGoodsDetailPresenter() {
            jdShopDataSource = new JDShopDataSource();
            integralDataSource = new IntegralDataSource();
        }

        @Override
        public void bind(JDGoodsDetailView view) {
            super.bind(view);
            UserSession.getInstance()
                    .getUserForRx()
                    .subscribeOn(Schedulers.io())
                    .compose(getView().bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<User>() {
                        @Override
                        public void accept(User user) throws Exception {
                            getView().onUser(user);
                        }
                    });
        }

        /**
         * 获取积分信息
         *
         * @param user
         * @return
         */
        private Single<OpenApiResult<IntegralUserBean>> getJDIntegralSingle(User user) {
            return Single.just(new RequestUserIntegral())
                    .doOnSuccess(new Consumer<RequestUserIntegral>() {
                        @Override
                        public void accept(RequestUserIntegral requestUserIntegral) throws Exception {
                            requestUserIntegral.setPhone(user.getPhone());
                            requestUserIntegral.setAutograph("123456");
                        }
                    })
                    .flatMap(new Function<RequestUserIntegral, SingleSource<OpenApiResult<IntegralUserBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<IntegralUserBean>> apply(RequestUserIntegral requestUserIntegral) throws Exception {
                            return integralDataSource.getUserIntegral(requestUserIntegral)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .compose(getOpenApiResultTranformer());
        }

        /**
         * 获取轮播图信息
         *
         * @return
         */
        private Single<OpenApiResult<JDGoodsListResultBean>> getJDGoodsImagesSingle(User userInfo, JDGoodsItemBean jdGoodsItemBean) {
            return Single.just(new RequestJDGoodsList())
                    .doOnSuccess(new Consumer<RequestJDGoodsList>() {
                        @Override
                        public void accept(RequestJDGoodsList requestJDGoodsList) throws Exception {
                            requestJDGoodsList.setPageIndex(PageInfo.INDEX_DEFAULT);
                            requestJDGoodsList.setPageSize(PageInfo.SIZE_DEFAULT);
                            requestJDGoodsList.setKySign("123456");
                            requestJDGoodsList.setPhone(userInfo.getPhone());
                            requestJDGoodsList.setSkuId(jdGoodsItemBean.getSku());

                        }
                    })
                    .flatMap(new Function<RequestJDGoodsList, SingleSource<OpenApiResult<JDGoodsListResultBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<JDGoodsListResultBean>> apply(RequestJDGoodsList requestJDGoodsList) throws Exception {
                            return jdShopDataSource.getJDGoodsList(requestJDGoodsList)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .compose(getOpenApiResultTranformer());
        }

        /**
         * 获取商品详情
         *
         * @param skuId
         * @return
         */
        private Single<OpenApiResult<JDGoodsDetailInfoBean>> getJDGoodsDetailInfoSingle(String skuId) {
            return Single
                    .just(new RequestJDGoodsDetail())
                    .doOnSuccess(new Consumer<RequestJDGoodsDetail>() {
                        @Override
                        public void accept(RequestJDGoodsDetail requestJDGoodsDetail) throws Exception {
                            requestJDGoodsDetail.setSkuId(skuId);
                        }
                    })
                    .flatMap(new Function<RequestJDGoodsDetail, SingleSource<? extends OpenApiResult<JDGoodsDetailInfoBean>>>() {
                        @Override
                        public SingleSource<? extends OpenApiResult<JDGoodsDetailInfoBean>> apply(RequestJDGoodsDetail requestJDGoodsDetail) throws Exception {
                            return jdShopDataSource.getJDGoodsDetail(requestJDGoodsDetail)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .compose(getOpenApiResultTranformer());
        }

        /**
         * 获取显示地址
         *
         * @param userInfo
         * @return
         */
        private Single<OpenApiResult<List<JDAddressBean>>> getJDAddresses(User userInfo) {
            return
                    Single.just(new RequestJDAddress())
                            .doOnSuccess(new Consumer<RequestJDAddress>() {
                                @Override
                                public void accept(RequestJDAddress requestJDAddress) throws Exception {
                                    requestJDAddress.setAddressType("0");
                                    requestJDAddress.setPhone(userInfo.getPhone());
                                }
                            })
                            .flatMap(new Function<RequestJDAddress, SingleSource<OpenApiResult<List<JDAddressBean>>>>() {
                                @Override
                                public SingleSource<OpenApiResult<List<JDAddressBean>>> apply(RequestJDAddress requestJDAddress) throws Exception {
                                    return jdShopDataSource.getJDShowAddress(requestJDAddress)
                                            .compose(getView().bindToLifecycleDestroy());
                                }
                            })
                            .compose(getOpenApiResultTranformer());

        }

        /**
         * 处理请求成功和异常
         *
         * @return
         */
        private <T> SingleTransformer<OpenApiResult<T>, OpenApiResult<T>> getOpenApiResultTranformer() {
            return new SingleTransformer<OpenApiResult<T>, OpenApiResult<T>>() {
                @Override
                public SingleSource<OpenApiResult<T>> apply(Single<OpenApiResult<T>> upstream) {
                    return upstream
                            .doOnSuccess(new Consumer<OpenApiResult<T>>() {
                                @Override
                                public void accept(OpenApiResult<T> result) throws Exception {
                                    if (result != null && result.isSuccess()) {

                                    } else {
                                        throw new ApiException(result);
                                    }
                                }
                            })
                            .doOnError(new Consumer<Throwable>() {
                                @Override
                                public void accept(Throwable e) throws Exception {

                                }
                            });
                }
            };
        }

        public void refresh(User userInfo, JDGoodsItemBean jdGoodsItemBean) {
            Single.zip(
                    getJDIntegralSingle(userInfo),
                    getJDGoodsImagesSingle(userInfo, jdGoodsItemBean),
                    getJDGoodsDetailInfoSingle(jdGoodsItemBean.getSku()),
                    getJDAddresses(userInfo),
                    new Function4<
                            OpenApiResult<IntegralUserBean>,
                            OpenApiResult<JDGoodsListResultBean>,
                            OpenApiResult<JDGoodsDetailInfoBean>,
                            OpenApiResult<List<JDAddressBean>>,
                            Data4ResultSet<OpenApiResult<IntegralUserBean>, OpenApiResult<JDGoodsListResultBean>, OpenApiResult<JDGoodsDetailInfoBean>, OpenApiResult<List<JDAddressBean>>>>() {
                        @Override
                        public Data4ResultSet<OpenApiResult<IntegralUserBean>, OpenApiResult<JDGoodsListResultBean>, OpenApiResult<JDGoodsDetailInfoBean>, OpenApiResult<List<JDAddressBean>>> apply(OpenApiResult<IntegralUserBean> integralUserBeanOpenApiResult, OpenApiResult<JDGoodsListResultBean> jdGoodsListResultBeanOpenApiResult, OpenApiResult<JDGoodsDetailInfoBean> jdGoodsDetailInfoBeanOpenApiResult, OpenApiResult<List<JDAddressBean>> listOpenApiResult) throws Exception {
                            return new Data4ResultSet<>(integralUserBeanOpenApiResult, jdGoodsListResultBeanOpenApiResult, jdGoodsDetailInfoBeanOpenApiResult, listOpenApiResult);
                        }
                    }
            )
                    .doOnSuccess(new Consumer<Data4ResultSet<OpenApiResult<IntegralUserBean>, OpenApiResult<JDGoodsListResultBean>, OpenApiResult<JDGoodsDetailInfoBean>, OpenApiResult<List<JDAddressBean>>>>() {
                        @Override
                        public void accept(Data4ResultSet<OpenApiResult<IntegralUserBean>, OpenApiResult<JDGoodsListResultBean>, OpenApiResult<JDGoodsDetailInfoBean>, OpenApiResult<List<JDAddressBean>>> data4ResultSet) throws Exception {
                            JDGoodsListResultBean jdGoodsListResultBean = data4ResultSet.data2.getData();
                            List<JDGoodsItemBean> jdGoodsItemBeans = jdGoodsListResultBean.getDatas();
                            if (jdGoodsItemBeans.size() > 0) {
                                ArrayList<JDGoodsSkuImageBean> jdGoodsSkuImageBeans = jdGoodsItemBeans.get(0).getSkuImage().get(jdGoodsItemBeans.get(0).getSku());
                                for (JDGoodsSkuImageBean skuImageBean : jdGoodsSkuImageBeans) {
                                    skuImageBean.getPath().replace("\\", "");
                                }
                            }
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SingleObserver<Data4ResultSet<OpenApiResult<IntegralUserBean>, OpenApiResult<JDGoodsListResultBean>, OpenApiResult<JDGoodsDetailInfoBean>, OpenApiResult<List<JDAddressBean>>>>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onSuccess(Data4ResultSet<OpenApiResult<IntegralUserBean>, OpenApiResult<JDGoodsListResultBean>, OpenApiResult<JDGoodsDetailInfoBean>, OpenApiResult<List<JDAddressBean>>> data4ResultSet) {
                            getView().refreshSuccess(data4ResultSet);
                        }

                        @Override
                        public void onError(Throwable e) {
                            if (e instanceof ApiException) {
                                getView().refreshServerFailed(e.getMessage());
                            } else {
                                getView().refreshNetFailed(e.getMessage());
                            }
                        }
                    });
        }

        /**
         * 检查配送地址是否有货
         *
         * @param userInfo
         * @param item
         * @param sku
         */
        public void checkGoodsAvailableByAddress(User userInfo, JDAddressModel item, String sku) {
            Single.just(new RequestJDCheckGoodsAvailable())
                    .doOnSuccess(new Consumer<RequestJDCheckGoodsAvailable>() {
                        @Override
                        public void accept(RequestJDCheckGoodsAvailable requestJDCheckGoodsAvailable) throws Exception {
                            String address = item.getAddressBean().getProvince() + "_" + item.getAddressBean().getCity() + "_" + item.getAddressBean().getCountry();
                            requestJDCheckGoodsAvailable.setAddress(address);
                            requestJDCheckGoodsAvailable.setPhone(userInfo.getPhone());
                            requestJDCheckGoodsAvailable.setSkuId(sku);
                        }
                    })
                    .flatMap(new Function<RequestJDCheckGoodsAvailable, SingleSource<OpenApiResult<JDCheckGoodsAvailableResultBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<JDCheckGoodsAvailableResultBean>> apply(RequestJDCheckGoodsAvailable requestJDCheckGoodsAvailable) throws Exception {
                            return jdShopDataSource.checkGoodsAvailable(requestJDCheckGoodsAvailable)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<JDCheckGoodsAvailableResultBean>() {
                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<JDCheckGoodsAvailableResultBean> result, JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean) {
                            getView().checkGoodsAvailableSuccess(jdCheckGoodsAvailableResultBean);
                        }

                        @Override
                        public void onApiError(OpenApiResult<JDCheckGoodsAvailableResultBean> result, int code, String msg) {
                            /**
                             0	操作成功
                             30000	操作失败
                             30026	值不能为空
                             30022	电话不能为空
                             32832	本礼品暂时无货请兑换其他礼品
                             */
                            if (32832 == code) {
                                getView().checkGoodsUnAvailableSuccess(result);
                            } else {
                                getView().checkGoodsAvailableServerFailed(msg);
                            }
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().checkGoodsAvailableNetFailed(e.getMessage());
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    });
        }

        /**
         * 首次检查配送地址是否有货
         *
         * @param userInfo
         * @param item
         * @param sku
         */
        public void checkGoodsAvailableByAddressFirst(User userInfo, JDAddressModel item, String sku) {
            Single.just(new RequestJDCheckGoodsAvailable())
                    .doOnSuccess(new Consumer<RequestJDCheckGoodsAvailable>() {
                        @Override
                        public void accept(RequestJDCheckGoodsAvailable requestJDCheckGoodsAvailable) throws Exception {
                            String address = item.getAddressBean().getProvince() + "_" + item.getAddressBean().getCity() + "_" + item.getAddressBean().getCountry();
                            requestJDCheckGoodsAvailable.setAddress(address);
                            requestJDCheckGoodsAvailable.setPhone(userInfo.getPhone());
                            requestJDCheckGoodsAvailable.setSkuId(sku);
                        }
                    })
                    .flatMap(new Function<RequestJDCheckGoodsAvailable, SingleSource<OpenApiResult<JDCheckGoodsAvailableResultBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<JDCheckGoodsAvailableResultBean>> apply(RequestJDCheckGoodsAvailable requestJDCheckGoodsAvailable) throws Exception {
                            return jdShopDataSource.checkGoodsAvailable(requestJDCheckGoodsAvailable)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<JDCheckGoodsAvailableResultBean>() {
                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<JDCheckGoodsAvailableResultBean> result, JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean) {
                            getView().checkGoodsAvailableSuccessFirst(jdCheckGoodsAvailableResultBean);
                        }

                        @Override
                        public void onApiError(OpenApiResult<JDCheckGoodsAvailableResultBean> result, int code, String msg) {
                            /**
                             0	操作成功
                             30000	操作失败
                             30026	值不能为空
                             30022	电话不能为空
                             32832	本礼品暂时无货请兑换其他礼品
                             */
                            if (32832 == code) {
                                getView().checkGoodsUnAvailableSuccessFirst(result);
                            } else {
                                getView().checkGoodsAvailableServerFailedFirst(msg);
                            }
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().checkGoodsAvailableNetFailedFirst(e.getMessage());
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    });
        }

        /**
         * 从地址管理返回后的更新数据操作
         *
         * @param jdAddressBeanSelected 返回选中的地址
         * @param addressBeanList 返回的所有地址列表
         */
        public void updateSelectedAddress(JDAddressBean jdAddressBeanSelected, List<JDAddressBean> addressBeanList, String sku, User userInfo) {
            if (addressBeanList == null) {
                addressBeanList = new ArrayList<>();
            }
            Observable.fromIterable(addressBeanList)
                    .map(new Function<JDAddressBean, JDAddressModel>() {
                        @Override
                        public JDAddressModel apply(JDAddressBean jdAddressBean) throws Exception {
                            JDAddressModel jdAddressModel = new JDAddressModel();
                            jdAddressModel.setAddressBean(jdAddressBean);
                            return jdAddressModel;
                        }
                    })
                    .toList()
                    .doOnSuccess(new Consumer<List<JDAddressModel>>() {
                        @Override
                        public void accept(List<JDAddressModel> addressModels) throws Exception {
                            if (addressModels.size() <= 0) {
                                // 删除了所有地址
                                return;
                            }
                            if (jdAddressBeanSelected == null && addressModels.size() <= 0) {
                                // 没有设置默认地址
                                return;
                            }
                            if (jdAddressBeanSelected == null && addressModels.size() > 0) {
                                // 设置第一个为默认地址
                                addressModels.get(0).setSelected(true);
                                getView().setSelectedAddress(addressModels.get(0));
                            } else {
                                for (JDAddressModel jdAddressModel : addressModels) {
                                    // 设置选中的默认地址
                                    if (jdAddressModel.getAddressBean().getId().equals(jdAddressBeanSelected.getId())) {
                                        jdAddressModel.setSelected(true);
                                        // 更新view选中的默认地址
                                        getView().setSelectedAddress(jdAddressModel);
                                    }
                                }
                            }
                        }
                    })
                    // 更新返回的地址列表
                    .doOnSuccess(new Consumer<List<JDAddressModel>>() {
                        @Override
                        public void accept(List<JDAddressModel> addressModels) throws Exception {
                            getView().setJdAddressModels(addressModels);
                        }
                    })
                    .toObservable()
                    .flatMap(new Function<List<JDAddressModel>, ObservableSource<JDAddressModel>>() {
                        @Override
                        public ObservableSource<JDAddressModel> apply(List<JDAddressModel> addressModels) throws Exception {
                            return Observable.fromIterable(addressModels);
                        }
                    })
                    .any(new Predicate<JDAddressModel>() {
                        @Override
                        public boolean test(JDAddressModel jdAddressModel) throws Exception {
                            /**
                             * 判断返回的地址列表有没有选中的地址
                             */
                            return jdAddressModel.isSelected();
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean hasSelected) throws Exception {
                            if (!hasSelected) {
                                // 没有选中的
                                if (getView().getJdAddressModels().size() > 0) {
                                    // 地址列表有地址，设置第一个为默认地址
                                    JDAddressModel jdAddressModel = getView().getJdAddressModels().get(0);
                                    jdAddressModel.setSelected(true);
                                    getView().setPreSelectedAddress(jdAddressModel);
                                    getView().setSelectedAddress(jdAddressModel);
                                    checkGoodsAvailableByAddressFromAddressManage(userInfo, jdAddressModel, sku);
                                } else {
                                    // 地址列表没有地址
                                    getView().setPreSelectedAddress(null);
                                    getView().setSelectedAddress(null);
                                    getView().updateGoodsAddressNoAddress();
                                }
                            } else {
                                // 有选中的
                                if (getView().getJdAddressModels().size() > 0) {
                                    getView().setPreSelectedAddress(getView().getSelectedAddress());
                                    getView().setSelectedAddress(getView().getSelectedAddress());
                                    checkGoodsAvailableByAddressFromAddressManage(userInfo, getView().getSelectedAddress(), sku);
                                } else {
                                    /**
                                     * 没有返回任何数据,设置
                                     */
                                    getView().setPreSelectedAddress(null);
                                    getView().setSelectedAddress(null);
                                    getView().updateGoodsAddressNoAddress();
                                }
                            }
                        }
                    });
        }

        /**
         * 商品详情从地址管理界面返回后检查当前的选中的地址是否有货可以配送
         * @param userInfo
         * @param jdAddressModel
         * @param sku
         */
        private void checkGoodsAvailableByAddressFromAddressManage(User userInfo, JDAddressModel jdAddressModel, String sku) {
            Single.just(new RequestJDCheckGoodsAvailable())
                    .doOnSuccess(new Consumer<RequestJDCheckGoodsAvailable>() {
                        @Override
                        public void accept(RequestJDCheckGoodsAvailable requestJDCheckGoodsAvailable) throws Exception {
                            String address = jdAddressModel.getAddressBean().getProvince() + "_" + jdAddressModel.getAddressBean().getCity() + "_" + jdAddressModel.getAddressBean().getCountry();
                            requestJDCheckGoodsAvailable.setAddress(address);
                            requestJDCheckGoodsAvailable.setPhone(userInfo.getPhone());
                            requestJDCheckGoodsAvailable.setSkuId(sku);
                        }
                    })
                    .flatMap(new Function<RequestJDCheckGoodsAvailable, SingleSource<OpenApiResult<JDCheckGoodsAvailableResultBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<JDCheckGoodsAvailableResultBean>> apply(RequestJDCheckGoodsAvailable requestJDCheckGoodsAvailable) throws Exception {
                            return jdShopDataSource.checkGoodsAvailable(requestJDCheckGoodsAvailable)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<JDCheckGoodsAvailableResultBean>() {
                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<JDCheckGoodsAvailableResultBean> result, JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean) {
                            /**
                             * 当前返回的选中地址有货
                             */
                            getView().checkGoodsAvailableFromAddressManageSuccess(jdCheckGoodsAvailableResultBean);
                        }

                        @Override
                        public void onApiError(OpenApiResult<JDCheckGoodsAvailableResultBean> result, int code, String msg) {
                            /**
                             0	操作成功
                             30000	操作失败
                             30026	值不能为空
                             30022	电话不能为空
                             32832	本礼品暂时无货请兑换其他礼品
                             */
                            if (32832 == code) {
                                /**
                                 * 没货
                                 */
                                getView().checkGoodsUnAvailableFromAddressManageSuccess(result);
                            } else {
                                getView().checkGoodsAvailableFromAddressManageServerFailed(msg);
                            }
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().checkGoodsAvailableNetFromAddressManageFailed(e.getMessage());
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    });
        }

        /**
         * 检测积分
         * @param integralUserBean
         * @param jdGoodsItemBean
         * @return
         */
        private Single<Boolean> getIntegralCheckSingle(IntegralUserBean integralUserBean, JDGoodsItemBean jdGoodsItemBean) {
            return Single.just(integralUserBean)
                    .map(new Function<IntegralUserBean, Boolean>() {
                        @Override
                        public Boolean apply(IntegralUserBean integralUserBean) throws Exception {
                            return integralUserBean.getTrueAvailableIntegral() > jdGoodsItemBean.getNeedScore();
                        }
                    });
        }

        // todo : 积分不够
        class IntegralNotEnoughException extends RuntimeException {
            public IntegralNotEnoughException(String message) {
                super(message);
            }
        }

        /**
         * 检查能否消费
         * @param userInfo
         * @return
         */
        private Single<OpenApiResult<JDCheckConsumeAvailableResultBean>> getConsumeCheckSingle(User userInfo) {
            RequestJDCheckConsumeAvailable requestJDCheckConsumeAvailable = new RequestJDCheckConsumeAvailable();
            requestJDCheckConsumeAvailable.setPhone(userInfo.getPhone());
            return jdShopDataSource.checkConsumeAvailable(requestJDCheckConsumeAvailable)
                    .compose(getView().bindToLifecycleDestroy());
        }

        // todo : 无法消费
        class ConsumeAvailableException extends RuntimeException {
            public ConsumeAvailableException(String message) {
                super(message);
            }
        }

        /**
         * 检查能够
         * @param userInfo
         * @return
         */
        private Single<OpenApiResult<JDCheckUploadAddressAvailableResultBean>> getCheckUploadAddressSingle(User userInfo) {
            RequestJDCheckUploadAddressAvailable requestJDCheckUploadAddressAvailable = new RequestJDCheckUploadAddressAvailable();
            requestJDCheckUploadAddressAvailable.setPhone(userInfo.getPhone());
            requestJDCheckUploadAddressAvailable.setValiteType("1");
            return jdShopDataSource.checkUploadAddressAvailable(requestJDCheckUploadAddressAvailable)
                    .compose(getView().bindToLifecycleDestroy());
        }

        /**
         * 兑换积分，配送是否有货检查
         * @param userInfo
         * @param selectedAddress
         * @param jdGoodsItemBean
         * @param integralUserBean
         */
        public void checkBeforeExchange(User userInfo, JDAddressModel selectedAddress, JDGoodsItemBean jdGoodsItemBean, IntegralUserBean integralUserBean) {
            Single.just(jdGoodsItemBean)
                    .doOnSuccess(new Consumer<JDGoodsItemBean>() {
                        @Override
                        public void accept(JDGoodsItemBean goodsItemBean) throws Exception {
                            int needScore = goodsItemBean.getNeedScore();
                            // 是否跨越用户 1:是
                            // 可用积分
                            int trueAvailableIntegral = integralUserBean.getTrueAvailableIntegral();
                            if (trueAvailableIntegral < needScore) {
                                // 积分不够
                                throw new RuntimeException("积分不够,无法兑换");
                            }
                        }
                    })
                    .map(new Function<JDGoodsItemBean, RequestJDCheckGoodsAvailable>() {
                        @Override
                        public RequestJDCheckGoodsAvailable apply(JDGoodsItemBean goodsItemBean) throws Exception {
                            RequestJDCheckGoodsAvailable requestJDCheckGoodsAvailable = new RequestJDCheckGoodsAvailable();
                            String address = selectedAddress.getAddressBean().getProvince() + "_" + selectedAddress.getAddressBean().getCity() + "_" + selectedAddress.getAddressBean().getCountry();
                            requestJDCheckGoodsAvailable.setAddress(address);
                            requestJDCheckGoodsAvailable.setPhone(userInfo.getPhone());
                            requestJDCheckGoodsAvailable.setSkuId(jdGoodsItemBean.getSku());
                            return requestJDCheckGoodsAvailable;
                        }
                    })
                    .flatMap(new Function<RequestJDCheckGoodsAvailable, SingleSource<OpenApiResult<JDCheckGoodsAvailableResultBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<JDCheckGoodsAvailableResultBean>> apply(RequestJDCheckGoodsAvailable requestJDCheckGoodsAvailable) throws Exception {
                            return jdShopDataSource.checkGoodsAvailable(requestJDCheckGoodsAvailable)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<JDCheckGoodsAvailableResultBean>() {
                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<JDCheckGoodsAvailableResultBean> result, JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean) {

                            if (jdCheckGoodsAvailableResultBean.getStatus().equals("1")) {
                                // 有货
                                getView().toExchangePage(jdCheckGoodsAvailableResultBean);
                            } else {
                                // 无货
                                ToastManager.show(getView().getContext(), result.getMsg());
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<JDCheckGoodsAvailableResultBean> result, int code, String msg) {
                            ToastManager.show(getView().getContext(), msg);
//                            getView().toExchangePage();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            ToastManager.show(getView().getContext(), e.getMessage());
//                            getView().toExchangePage();
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    });
        }

        /**
         * 立即兑换
         *
         * @param userInfo
         * @param selectedAddress
         * @param integralUserBean
         */
        public void toExchange(User userInfo, JDAddressModel selectedAddress, IntegralUserBean integralUserBean, JDGoodsItemBean jdGoodsItemBean) {
            getIntegralCheckSingle(integralUserBean, jdGoodsItemBean)
                    .subscribeOn(Schedulers.io())
                    .doOnSuccess(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean integralEnought) throws Exception {
                            if (!integralEnought) {
                                throw new IntegralNotEnoughException("积分不够，无法兑换。");
                            }
                        }
                    })
                    .flatMap(new Function<Boolean, SingleSource<OpenApiResult<JDCheckConsumeAvailableResultBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<JDCheckConsumeAvailableResultBean>> apply(Boolean integralEnought) throws Exception {
                            return getConsumeCheckSingle(userInfo);
                        }
                    })
                    // todo :
                    .doOnSuccess(new Consumer<OpenApiResult<JDCheckConsumeAvailableResultBean>>() {
                        @Override
                        public void accept(OpenApiResult<JDCheckConsumeAvailableResultBean> jdCheckConsumeAvailableResultBeanOpenApiResult) throws Exception {
                            if (jdCheckConsumeAvailableResultBeanOpenApiResult.isSuccess()) {

                            } else {

                            }
                        }
                    });
        }
    }
}
